package com.bizmda.bizsip.sample.source.longtcpnetty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @Author: 史正烨
 * @Date: 2022/3/1 9:53 上午
 * @Description:
 */
@Slf4j
public class SampleDecoder extends ByteToMessageDecoder {    private short length = -1;
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (length == -1) {
            if (in.readableBytes() < 2) {
                return;
            }
            this.length = in.readShort();
        }
//        log.debug("decode:{},{}",this.length,in.readableBytes());
        if (in.readableBytes() < this.length) {
            return;
        }
        byte[] data = new byte[this.length] ;
        if (this.length > 0) {
            in.readBytes(data);
        }
        SampleMessage sampleMessage = SampleMessage.builder().length(this.length).data(data).build();
        out.add(sampleMessage) ;
        this.length = -1;
    }
}
